<script setup>
import VideoCategoryApi from "@/api/VideoCategoryApi.js";
import {onMounted, reactive, ref, watch} from "vue";
import {Plus, Delete} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";

const state = reactive({
  categoryTree: [],
  defaultExpendKeys:[],
  dialog:{
    updateDialogVisible:false,
    addDialogVisiable:false
  },
  addCategoryDto:{
    parentId:null,
    parentName:null,
    categoryName:null
  },
  updateCategoryDto:{
    oldCategoryName:null,
    categoryId:null,
    categoryName:null
  }

})
const treeProps = {
  children: 'children',
  label: 'categoryName',
}
const getVideoCategoryTree = () => {
  VideoCategoryApi.getVideoCategoryTree().then(res => {
    state.categoryTree = res.data
  })
}
const treeRef = ref()
const filterText = ref('')
watch(filterText, (val) => {
  treeRef.value.filter(val)
})
const filterNode = (value, tree) => {
  if (!value) return true
  return tree.categoryName.includes(value)
}
onMounted(() => {
  getVideoCategoryTree()
})
const openAddDialog = (parentCategory)=>{
  state.addCategoryDto={}
  state.defaultExpendKeys.push(parentCategory.categoryId)
  state.addCategoryDto.parentId = parentCategory.categoryId
  state.addCategoryDto.parentName = parentCategory.categoryName
  state.dialog.addDialogVisiable = true
}
const openUpdateDialog = (category)=>{
  state.updateCategoryDto = {}
  state.defaultExpendKeys.push(category.categoryId)
  VideoCategoryApi.getVideoCategoryInfo(category.categoryId).then(res=>{
    if (!res.flag){
      ElMessage.error(res.message)
      return
    }
    state.updateCategoryDto.categoryId = res.data.categoryId
    state.updateCategoryDto.oldCategoryName = res.data.categoryName
    state.updateCategoryDto.categoryName = res.data.categoryName
    state.dialog.updateDialogVisible=true
  })
}
const addCategory=()=>{
  VideoCategoryApi.addCategory(state.addCategoryDto).then(res=>{
    if (!res.flag){
      ElMessage.error(res.message)
      return
    }
    ElMessage.success("添加成功!")
    state.dialog.addDialogVisiable=false
    getVideoCategoryTree()
  })
}
const updateCategory=()=>{
  VideoCategoryApi.updateCategory(state.updateCategoryDto).then(res=>{
    if (!res.flag){
      ElMessage.error(res.message)
      return
    }
    ElMessage.success("修改成功!")
    state.dialog.updateDialogVisible=false
    getVideoCategoryTree()
  })
}

const confirmDeleteBox = (category,isBatch)=>{
  let deleteIds=[]
  if (isBatch){
    deleteIds = treeRef.value.getCheckedKeys()
  }else {
   state.defaultExpendKeys.push(category.parentId)
    deleteIds.push(category.categoryId)
  }
  if (deleteIds.length===0){
    ElMessage.error("请选择待删除的分类!")
    return
  }
 ElMessageBox.confirm(
      '确定删除该分类吗（同时会删除该分类下的所有分类）?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        VideoCategoryApi.deleteCategory(deleteIds).then(res=>{
          if (!res.flag){
            ElMessage.error("删除失败")
            return
          }
          ElMessage.success("删除成功")
          getVideoCategoryTree()
        })
      })
}
</script>
<template>
  <el-card style="--el-card-padding: 10px;z-index: 10">
    <p style="display: flex;align-items: center">
      <el-button type="primary" size="small" :icon="Plus" @click="openAddDialog">添加</el-button>
      <el-button type="danger" size="small"  :icon="Delete" @click="confirmDeleteBox(null,true)">删除</el-button>
      <el-input v-model="filterText" style="margin-left: 10px;width: 30%" placeholder="查找"/>
    </p>
  </el-card>

  <el-card style="--el-card-padding: 10px;margin-top: 10px">
    <el-tree ref="treeRef" :data="state.categoryTree" :props="treeProps" style="width: 50%;"
             :filter-node-method="filterNode"
             :default-expanded-keys="state.defaultExpendKeys"
             node-key="categoryId"
             highlight-current :expand-on-click-node="false" accordion show-checkbox>
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
           <el-button text size='small' type="primary" @click="openAddDialog(data)" v-if="data.parentId===-1">添加</el-button>
           <el-button text size='small' type="warning" @click="openUpdateDialog(data)">修改</el-button>
           <el-button text size='small' type="danger" @click="confirmDeleteBox(data,false)">删除</el-button>
          </span>
        </span>
      </template>
    </el-tree>
  </el-card>
<!-- 添加对话框 -->
  <el-dialog v-model="state.dialog.addDialogVisiable" title="添加分类" width="30%" center style="border-radius: 10px" :close-on-click-modal="false">
    <el-form :model="state.addCategoryDto" >
      <el-form-item label="父级分类"  v-if="state.addCategoryDto.parentId!=null && state.addCategoryDto.parentId!==-1">
        <el-input disabled v-model="state.addCategoryDto.parentName" />
      </el-form-item>
      <el-form-item label="分类名称" :rules="[{required: true, message: '请填写分类名称!', trigger: 'blue'}]">
        <el-input v-model="state.addCategoryDto.categoryName" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialog.addDialogVisiable = false">取消</el-button>
        <el-button type="primary" @click="addCategory">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
<!--修改对话框-->
  <el-dialog v-model="state.dialog.updateDialogVisible" :title="`修改分类-【${state.updateCategoryDto.oldCategoryName}】`"
             width="30%" center style="border-radius: 10px" :close-on-click-modal="false">
    <el-form :model="state.updateCategoryDto" >
      <el-form-item label="分类名称" >
        <el-input v-model="state.updateCategoryDto.categoryName" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialog.updateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateCategory">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style lang="less">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
